//
//  AFHttpTool.m
//  THHuaLv
//
//  Created by TianHe_Wsk on 15/5/21.
//  Copyright (c) 2015年 TH_wsk. All rights reserved.
//

#import "AFHttpTool.h"
#import "FMDataSqlManger.h" //数据库操作
#import "AppDelegate.h"


@implementation AFHttpTool

#pragma mark 检测网路状态
+(void)netWorkStatussuccess:(void (^)(int responseObject))success
{
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // WiFi
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)  {
        
        if (success) {
            success(status);
        }
        
        
    }];
}


#pragma TH Http 自己写的请求
+(void)getJsonDatawithUrl:(NSString *)url   success:(void (^)(id responseObject))success fail:(void (^)(id responseObject,NSError*error))fail{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    [session GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(nil,error);
        }
    }];
}


/**
 *post 提交请求到服务器
 */
+(void)postJsonDatawithUrl:(NSString *)url success:(void (^)(id responseObject))success fail:(void (^)(id responseObject,NSError*error))fail {
            //不走缓存的
    NSString *httpUrl=[[THMangerTool getUsedHost] stringByAppendingString:url];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    [manager POST:httpUrl parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(nil,error);
        }
    }]; 
}



/**
 *post 提交请求到服务器
 */
+(void)postJsonDatawithUrl:(NSString *)url   parameters:(id)parameters   success:(void (^)(id responseObject))success fail:(void (^)(id responseObject,NSError*error))fail {
    if(parameters){
    parameters=[parameters mutableCopy];
    }
    if([parameters isKindOfClass:[NSMutableDictionary class]]){
        [parameters setValue:[[UIDevice currentDevice] model] forKey:@"phoneModel"];
        [parameters setValue:[NSString stringWithFormat:@"%@",[THMangerTool getVersion:NO]]  forKey:@"appVersion"];
        [parameters setValue:@"ios" forKey:@"phoneType"];
        [parameters setObject:@"zh" forKey:@"language"];
        if([THMangerTool isLogin]){
            [parameters setValue:[NSString stringWithFormat:@"%@",[THMangerTool getKey]] forKey:@"key"];
        }
    }
    else{
        NSMutableDictionary *para=[NSMutableDictionary dictionaryWithDictionary:parameters];
        [para setValue:[[UIDevice currentDevice] model] forKey:@"phoneModel"];
        [para setValue:[NSString stringWithFormat:@"%@",[THMangerTool getVersion:NO]]  forKey:@"appVersion"];
        [para setValue:@"ios" forKey:@"phoneType"];
        
        [para setObject:@"zh" forKey:@"language"];
        
        if([THMangerTool isLogin]){
            [para setValue:[NSString stringWithFormat:@"%@",[THMangerTool getKey]] forKey:@"key"];
        }
        parameters = [NSMutableDictionary dictionaryWithDictionary:para];
    }

    if(NSLanguageEnglish==[THMangerTool getLanageType]){
      [parameters setObject:@"en" forKey:@"language"];
    }
    
    NSMutableDictionary *tempDict = [parameters mutableCopy];
    
    //加密请求字符串
     NSString *requsetJson=[THMangerTool encryption:parameters encrypt:YES];
    
        parameters=[NSDictionary dictionaryWithObjectsAndKeys:requsetJson,@"request",nil];

        //不走缓存的
        NSString *httpUrl =  [[THMangerTool getUsedHost] stringByAppendingString:url];
    
    NSLog(@"请求头是%@",httpUrl);
    NSLog(@"%@?request=%@",httpUrl,requsetJson);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        // 设置超时时间
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
         manager.requestSerializer.timeoutInterval = 30.0f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
        
    
        // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情

        [manager POST:httpUrl parameters:[parameters copy] progress:^(NSProgress * _Nonnull uploadProgress) {
 
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObjects) {
            if ( success) {
                NSLog(@"请求成功，请求头%@=======加密前的参数%@",url,tempDict);

                NSDictionary *responseObject=[THMangerTool decryption:[responseObjects objectForKey:@"result"] encrypt:YES];
                NSMutableDictionary *result=[responseObject mutableCopy];
                
                
                NSString *info=[UtilCheck comparelowercaseString:[NSString stringWithFormat:@"%@",[[result objectForKey:@"head"] objectForKey:@"info"]] isLower:YES];
            
                if(0==[[[result  objectForKey:@"head"] objectForKey:@"status"] intValue]&&( [UtilCheck compareString:info ContaincompareString2:@"未登录"]||[info isEqualToString:@"login out"] || [info isEqualToString:@"用户凭证不存在"] )){
                    [result setObject:@"服务器网络异常，请重新登录" forKey:@"info"];
                    [THMangerTool removeAccount];
                    [APPDELEGATESelf Relogin];
                }
 
              success(result);
 
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败，请求头%@=======加密前的参数%@",url,tempDict);

            if (fail) {
                fail(nil,error);
            }
        }];
    
}


+ (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}

/**
 *post 提交附件
 */
+(void)postFilewithUrl:(NSString *)url   parameters:(id)parameters  file:(NSMutableArray*)filePaths  success:(void (^)(id responseObject))success progress:(void (^)(NSProgress * uploadProgress))progress fail:(void (^)(id responseObject,NSError*error))fail{
    
    if([parameters isKindOfClass:[NSMutableDictionary class]]){
        [parameters setValue:[[UIDevice currentDevice] model] forKey:@"phoneModel"];
        [parameters setValue:[NSString stringWithFormat:@"%@",[THMangerTool getVersion:NO]]  forKey:@"appVersion"];
        [parameters setValue:@"ios" forKey:@"phoneType"];
                 [parameters setObject:@"zh" forKey:@"language"];
        if([THMangerTool isLogin]){
            [parameters setValue:[NSString stringWithFormat:@"%@",[THMangerTool getKey]] forKey:@"key"];
        }
    }
    else{
        NSMutableDictionary *para=[NSMutableDictionary dictionaryWithDictionary:parameters];
        [para setValue:[[UIDevice currentDevice] model] forKey:@"phoneModel"];
        [para setValue:[NSString stringWithFormat:@"%@",[THMangerTool getVersion:NO]]  forKey:@"appVersion"];
        [para setValue:@"ios" forKey:@"phoneType"];
                    [parameters setObject:@"zh" forKey:@"language"];
        if([THMangerTool isLogin]){
            [para setValue:[NSString stringWithFormat:@"%@",[THMangerTool getKey]] forKey:@"key"];
        }
        parameters = [NSMutableDictionary dictionaryWithDictionary:para];
    }
    
    if(NSLanguageEnglish==[THMangerTool getLanageType]){
        [parameters setObject:@"en" forKey:@"language"];
    }
    NSMutableDictionary *tempDict = [parameters mutableCopy];

    //加密请求字符串
    NSString *requsetJson=[THMangerTool encryption:parameters encrypt:YES];
    
    parameters=[NSDictionary dictionaryWithObjectsAndKeys:requsetJson,@"request",nil];
    
    NSString *httpUrl=[[THMangerTool getUsedHost] stringByAppendingString:url];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
 
    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
 
    [manager POST:httpUrl parameters:[parameters mutableCopy] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i=0; i<[filePaths count]; i++) {
 
            UIImage *first =[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@",[filePaths objectAtIndex:i]]];
            NSData *data =UIImageJPEGRepresentation(first, 0.8) ;
 
              [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"DT_%@.png",[UtilCheck DateToTimestamp]] mimeType:@"image/png"];
            
 
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if(progress){
            progress(uploadProgress);
        }
 
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            
            NSLog(@"请求成功，请求头%@=======加密前的参数%@",url,tempDict);

            
            NSDictionary *resObject=[THMangerTool decryption:[responseObject objectForKey:@"result"] encrypt:YES];
            NSMutableDictionary *result=[resObject mutableCopy];
                        
            NSString *info=[UtilCheck comparelowercaseString:[NSString stringWithFormat:@"%@",[[result objectForKey:@"head"] objectForKey:@"info"]] isLower:YES];
            
            if(0==[[[result  objectForKey:@"head"] objectForKey:@"status"] intValue]&&( [UtilCheck compareString:info ContaincompareString2:@"未登录"]||[info isEqualToString:@"login out"])){
                [result setObject:@"服务器网络异常，请重新登录" forKey:@"info"];
                [THMangerTool removeAccount];
                [APPDELEGATESelf Relogin];
            }
            
            
            success(result);
        
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败，请求头%@=======加密前的参数%@",url,tempDict);

        if (fail) {
            fail(nil,error);
        }
    }];
    
}


/**
 * 附件取数据下载
 */
+ (void)fileDownloadWithUrl:(NSString*)urlStr  path:(NSString *)strpath success:(void (^)(id responseObject))success{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断MyImageFolder文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:strpath];
    if(!fileExists)
    {
        [fileManager createDirectoryAtPath:strpath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *fileOldPath=[NSString stringWithFormat:@"%@/%@",strpath,[self Filename:urlStr]];
    if([ UtilCheck Ishavefile:fileOldPath]){
        //文件存在直接放回
        
        NSURL *fileURL = [NSURL fileURLWithPath:fileOldPath];
        if (success) {
            success(fileURL);
        }

    }
    
    
    
}
/**
 * 附件 下载
 */
+ (void)fileDownloadWithUrl:(NSString*)urlStr  path:(NSString *)strpath success:(void (^)(id responseObject,BOOL ishave ))success fail:(void (^)(id responseObject,NSError*error))fail{
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断MyImageFolder文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:strpath];
    if(!fileExists)
    {
        [fileManager createDirectoryAtPath:strpath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *fileOldPath=[NSString stringWithFormat:@"%@/%@",strpath,[self Filename:urlStr]];
    if([ UtilCheck Ishavefile:fileOldPath]){
    //文件存在直接放回
 
         NSURL *fileURL = [NSURL fileURLWithPath:fileOldPath];
        if (success) {
            success(fileURL,YES);
        }
        return;
    }
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    
    NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",urlString);
    
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 指定下载文件保存的路径
        // 将下载文件保存在缓存路径中
        NSString *path = [strpath stringByAppendingPathComponent:response.suggestedFilename];
        
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        //        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        
 
        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if(!error){
 
            NSString *path = [strpath stringByAppendingPathComponent:response.suggestedFilename];
            NSURL *fileURL = [NSURL fileURLWithPath:path];
 
            if (success) {
                success(fileURL,NO);
            }
 
        }
        else{
            if (fail) {
                fail(nil,error);
            }
        }
    }];
    
    [task resume];
}

/**
 文件下载
 @param urlStr  下载地址
 @param strpath 下载后文件保存路径
 @param success 下载成功后回调
 @param fail    下载失败后回调
 */
+ (void)downloadFileWithURL:(NSString *)urlStr path:(NSString *)strpath success:(void (^)(id responseObject))success fail:(void (^)(id responseObject,NSError*error))fail {
    
    // 检测是否有相同命名的文件,如果有删除后,没有新建
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 判断MyImageFolder文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:strpath];
    
    if(!fileExists)
    {
        [fileManager createDirectoryAtPath:strpath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    else {
        [fileManager removeItemAtPath:strpath error:nil];
        [fileManager createDirectoryAtPath:strpath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // 文件下载
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];

    NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3];

    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 指定下载文件保存的路径
        // 将下载文件保存在缓存路径中
        NSString *path = [strpath stringByAppendingPathComponent:response.suggestedFilename];
        
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        // NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        return fileURL;
       
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        if(!error){
            
            NSString *path = [strpath stringByAppendingPathComponent:response.suggestedFilename];
            NSURL *fileURL = [NSURL fileURLWithPath:path];
            
            if (success) {
                success(fileURL);
                NSLog(@"fileURL is -- %@",fileURL);
            }
        }
        else {
            if (fail) {
                fail(nil,error);
                 NSLog(@"download failed");
            }
        }
    }];
    
    [task resume];
}


+(NSString*)Filename:(NSString*)httpUrl{
    NSString *result=@"";
    
    if([UtilCheck DataIsNuLL:httpUrl]){
        return result;
    }
        NSArray *stringArray=[httpUrl componentsSeparatedByString:@"/"];
        if(stringArray.count>0){
            result=[NSString stringWithFormat:@"%@%@,",result,stringArray[stringArray.count-1]];
        }
 
    if([result hasSuffix:@","]){
        result=[result substringToIndex:result.length-1];
        
    }
    return result;
}


/**
 读取服务器上TXT文本内容

 @param URLStr  文本地址
 @param success 请求成功回调
 @param fail    请求失败回调
 */
+ (NSURLSessionTask *)getStringFromTxtFileURLString:(NSString *)URLStr completion:(void (^)(NSString *resultString,NSError *error))completion {
    
    // 快捷方式获得session对象
    
    if (![URLStr hasSuffix:@".txt"]) {
        NSError *error;
        completion(@"",error);
        return nil;
    }
    
    NSURLSession *session = [NSURLSession sharedSession];

    NSURL *URL = [NSURL URLWithString:URLStr];
    
    // 通过URL初始化task,在block内部可以直接对返回的数据进行处理
    NSURLSessionTask *task = [session dataTaskWithURL:URL
                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError* error) {
                                        
                                        if (error) {
                                            completion(@"",error);
                                        }
                                        else {
                                            NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            completion(dataString,error);
                                        }
                                    }];
    // 启动任务
    [task resume];
    return task;
    
}

@end
